package ext.acae2.dms.web.input;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.log4j.Logger;

import wt.log4j.LogR;
import wt.util.WTProperties;

public class UploadFileProcessor {

    private static final Logger LOGGER = LogR.getLogger(UploadFileProcessor.class.getName());
    
    public File upload(List<DiskFileItem> parameters) throws Exception {
        LOGGER.debug("> Start upload");
        
        // Get Path
        String serverFolderPath = getServerFolder();
        LOGGER.debug("serverFolderPath: " + serverFolderPath);
        
        File serverFile = null;
        
        for (DiskFileItem item : parameters) {
            if (item.isFormField()) {
                // Get supplier name from form
                String name = item.getFieldName();
                String supplierName = item.getString();
                LOGGER.debug("name: " + name);
                LOGGER.debug("supplierName: " + supplierName);
            }
            else {
                // Get and upload file from form
                String fileName = item.getName();
                LOGGER.debug("fileName: " + fileName);
                
                if (fileName.contains("\\")) {
                    fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    LOGGER.debug("new fileName: " + fileName);
                }
                
                if (fileName != null) {
                    serverFile = new File(serverFolderPath + File.separator + fileName);
                    item.write(serverFile);
                    LOGGER.debug("upload done!");
                }
            }
        }
        
        LOGGER.debug("> End upload");
        return serverFile;
    }
    
    public String getServerFolder() throws IOException {
        
        String uploadPath = WTProperties.getLocalProperties().getProperty("wt.temp") + File.separator + "dataImport";
        LOGGER.debug("uploadPath: " + uploadPath);
        
        File uploadFolder = new File(uploadPath);
        if (!uploadFolder.exists()) {
            LOGGER.debug("create new folder: " + uploadPath);
            uploadFolder.mkdir();
        }
        
        return uploadPath;
    }
}
